import React from 'react';
import ReactMarkdown from 'react-markdown';
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { prism } from 'react-syntax-highlighter/dist/esm/styles/prism';

// 自定义代码块组件
const CodeBlock = ({ children, className, inline }) => {
  const language = className ? className.replace('language-', '') : 'text';
  const content = String(children);

  // 如果是行内代码（单个反引号），使用简单的code标签
  if (inline) {
    return <code className="search-inline-code">{content}</code>;
  }

  // 对于代码块，检查内容长度和复杂度
  // 如果内容很短且简单（如单个数字、简单数组），使用行内样式
  const isSimpleContent = content.length < 50 &&
                          !content.includes('\n') &&
                          !content.includes('function') &&
                          !content.includes('class') &&
                          !content.includes('import') &&
                          !content.includes('public') &&
                          !content.includes('private');

  if (isSimpleContent) {
    return <code className="search-inline-code">{content}</code>;
  }

  // 如果是复杂代码块（三个反引号），使用语法高亮
  return (
    <SyntaxHighlighter
      language={language}
      style={prism}
      customStyle={{
        margin: '12px 0',
        borderRadius: '8px',
        fontSize: '14px',
        lineHeight: '1.5',
        backgroundColor: '#f8f9fa',
        border: '1px solid #e9ecef'
      }}
      showLineNumbers={true}
      wrapLines={true}
    >
      {content.replace(/\n$/, '')}
    </SyntaxHighlighter>
  );
};

const SearchControlPanel = ({
  // 面板状态
  leftPanelWidth,
  activeTab,
  setActiveTab,

  // 数据相关
  data,
  dataMode,
  setDataMode,
  customData,
  setCustomData,
  dataError,
  dataSize,
  setDataSize,
  handleGenerateData,
  handleCustomDataChange,

  // 搜索设置
  target,
  setTarget,
  targetError,
  handleTargetChange,

  // 动画控制
  animationSpeed,
  setAnimationSpeed,

  // 搜索控制
  isRunning,
  isPaused,
  isStepping,
  startSearch,
  stepSearch,
  pauseSearch,
  stopSearch,

  // 状态信息
  status,
  currentStep,
  totalSteps,

  // AI聊天
  chatMessages,
  chatInput,
  setChatInput,
  isAIResponding,
  handleSendMessage,
  suggestedQuestions,
  handleSuggestedQuestionClick,

  // 算法名称（用于显示）
  algorithmName = '搜索'
}) => {
  return (
    <div
      className="search-control-panel"
      style={{ width: `${leftPanelWidth}px` }}
    >
      {/* 横向导航栏 */}
      <div className="search-panel-tabs">
        <button
          className={`search-tab-button ${activeTab === 'settings' ? 'active' : ''}`}
          onClick={() => setActiveTab('settings')}
        >
          ⚙️ 参数设置
        </button>
        <button
          className={`search-tab-button ${activeTab === 'chat' ? 'active' : ''}`}
          onClick={() => setActiveTab('chat')}
        >
          💬 AI助手
        </button>
      </div>

      {/* 参数设置面板 */}
      {activeTab === 'settings' && (
        <div className="search-settings-panel">
          {/* 数据设置 */}
          <div className="search-setting-group">
            <h3>数据设置</h3>

            <div className="search-data-mode-selector">
              <label>
                <input
                  type="radio"
                  name="dataMode"
                  value="random"
                  checked={dataMode === 'random'}
                  onChange={(e) => setDataMode(e.target.value)}
                />
                随机生成数据
              </label>
              <label>
                <input
                  type="radio"
                  name="dataMode"
                  value="custom"
                  checked={dataMode === 'custom'}
                  onChange={(e) => setDataMode(e.target.value)}
                />
                自定义数据
              </label>
            </div>

            {/* 数据大小输入 - 在随机模式下显示 */}
            {dataMode === 'random' && (
              <div className="search-data-size-input">
                <label>数据大小：</label>
                <input
                  type="number"
                  min="5"
                  max="20"
                  value={dataSize}
                  onChange={(e) => setDataSize(parseInt(e.target.value) || 10)}
                />
              </div>
            )}

            {/* 自定义数据输入 - 在自定义模式下显示 */}
            {dataMode === 'custom' && (
              <div className="search-custom-data-input">
                <label>输入数据（用逗号分隔）：</label>
                <textarea
                  value={customData}
                  onChange={handleCustomDataChange}
                  placeholder="例如：1, 3, 5, 7, 9, 11, 13, 15"
                  rows={3}
                />
                {dataError && <div className="search-error-message">{dataError}</div>}
              </div>
            )}

            {/* 生成数据按钮 - 在任何模式下都显示 */}
            <button className="search-generate-btn" onClick={handleGenerateData}>
              生成数据
            </button>

            <div className="search-current-data">
              <strong>当前数据：</strong>
              <div className="search-data-display-text">
                {data.length > 0 ? `[${data.join(', ')}]` : '无数据'}
              </div>
            </div>
          </div>

          {/* 搜索设置 */}
          <div className="search-setting-group">
            <h3>🎯 搜索设置</h3>
            <div className="search-target-input">
              <label>目标值：</label>
              <input
                type="number"
                value={target}
                onChange={handleTargetChange}
                placeholder="输入要查找的数字"
              />
              {targetError && <div className="search-error-message">{targetError}</div>}
            </div>
          </div>

          {/* 动画设置 */}
          <div className="search-setting-group">
            <h3>🎬 动画设置</h3>
            <div className="search-speed-control">
              <label>动画速度：</label>
              <input
                type="range"
                min="100"
                max="2000"
                value={animationSpeed}
                onChange={(e) => setAnimationSpeed(parseInt(e.target.value))}
              />
              <span>{animationSpeed}ms</span>
            </div>
          </div>

          {/* 控制按钮 */}
          <div className="search-setting-group">
            <h3>🎮 搜索控制</h3>
            <div className="search-control-buttons">
              <button
                className="search-control-btn search-start"
                onClick={startSearch}
                disabled={isRunning && !isPaused}
              >
                ▶️ 开始搜索
              </button>
              <button
                className="search-control-btn search-step"
                onClick={stepSearch}
                disabled={isRunning && !isPaused && !isStepping}
              >
                ⏭️ 单步执行
              </button>
              <button
                className="search-control-btn search-pause"
                onClick={pauseSearch}
                disabled={!isRunning || isPaused}
              >
                ⏸️ 暂停
              </button>
              <button
                className="search-control-btn search-stop"
                onClick={stopSearch}
                disabled={!isRunning && !isPaused}
              >
                ⏹️ 停止
              </button>
            </div>
          </div>

          {/* 状态信息 */}
          <div className="search-setting-group">
            <h3>📈 状态信息</h3>
            <div className="search-status-info">
              <div className="search-status-item">
                <span className="search-label">状态：</span>
                <span className={`search-value ${status.includes('完成') ? 'search-success' : ''}`}>
                  {status}
                </span>
              </div>
              <div className="search-status-item">
                <span className="search-label">进度：</span>
                <span className="search-value">{currentStep} / {totalSteps || '?'}</span>
              </div>
              <div className="search-status-item">
                <span className="search-label">数据量：</span>
                <span className="search-value">{data.length} 个元素</span>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* 智能问答面板 */}
      {activeTab === 'chat' && (
        <div className="search-chat-panel">
          {/* 猜你想问 */}
          <div className="search-quick-questions">
            <h3>💡 猜你想问</h3>
            <div className="search-question-buttons">
              {suggestedQuestions.map((question, index) => (
                <button
                  key={index}
                  className="search-question-btn"
                  onClick={() => handleSuggestedQuestionClick(question)}
                >
                  {question}
                </button>
              ))}
            </div>
          </div>

          {/* 聊天区域 */}
          <div className="search-chat-area">
            <div className="search-chat-messages">
              {chatMessages.length === 0 ? (
                <div className="search-welcome-message">
                  <div className="search-ai-avatar">🤖</div>
                  <div className="search-message-content">
                    <p>你好！我是你的AI算法助手。</p>
                    <p>你可以问我关于{algorithmName}的任何问题，或者点击上面的快捷问题开始对话！</p>
                  </div>
                </div>
              ) : (
                chatMessages.map((message) => (
                  <div key={message.id} className={`search-message ${message.type}`}>
                    <div className="search-message-avatar">
                      {message.type === 'user' ? '👤' : '🤖'}
                    </div>
                    <div className="search-message-content">
                      {message.type === 'ai' ? (
                        <ReactMarkdown
                          components={{
                            code: CodeBlock
                          }}
                        >
                          {message.content}
                        </ReactMarkdown>
                      ) : (
                        <p>{message.content}</p>
                      )}
                      <div className="search-message-time">
                        {message.timestamp.toLocaleTimeString()}
                      </div>
                    </div>
                  </div>
                ))
              )}
              {isAIResponding && (
                <div className="search-message ai">
                  <div className="search-message-avatar">🤖</div>
                  <div className="search-message-content">
                    <div className="search-typing-indicator">
                      <span></span>
                      <span></span>
                      <span></span>
                    </div>
                  </div>
                </div>
              )}
            </div>

            {/* 输入区域 */}
            <div className="search-chat-input-area">
              <div className="search-input-container">
                <input
                  type="text"
                  value={chatInput}
                  onChange={(e) => setChatInput(e.target.value)}
                  placeholder={`问我关于${algorithmName}的任何问题...`}
                  onKeyPress={(e) => {
                    if (e.key === 'Enter' && !e.shiftKey) {
                      e.preventDefault();
                      handleSendMessage(chatInput);
                    }
                  }}
                  disabled={isAIResponding}
                />
                <button
                  onClick={() => handleSendMessage(chatInput)}
                  disabled={!chatInput.trim() || isAIResponding}
                  className="search-send-btn"
                >
                  📤
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default SearchControlPanel;
